let privacyHandler
let privacyResolves = new Set()
let closeOtherPagePopUpHooks = new Set()

wx.onNeedPrivacyAuthorization(resolve => {
  if (typeof privacyHandler === 'function') {
    privacyHandler(resolve)
  }
})

const closeOtherPagePopUp = (closePopUp) => {
  closeOtherPagePopUpHooks.forEach(hook => {
    if (closePopUp !== hook) {
      hook()
    }
  })
}

Component({
  data: {
    title: "用户协议和隐私政策提示",
    desc1: "",
    urlTitle: "",
    desc2: "",
    innerShow: false,
  },
  lifetimes: {
    attached: function () {
      const closePopUp = () => {
        this.disPopUp()
      }
      privacyHandler = resolve => {
        privacyResolves.add(resolve)
        this.popUp()
        closeOtherPagePopUp(closePopUp)
      }
      closeOtherPagePopUpHooks.add(closePopUp)
      this.closePopUp = closePopUp
    },
    detached: function () {
      closeOtherPagePopUpHooks.delete(this.closePopUp)
    }
  },
  methods: {
    handleAgree(e) {
      this.disPopUp()
      privacyResolves.forEach(resolve => {
        resolve({
          event: 'agree',
          buttonId: 'agree-btn'
        })
      })
      privacyResolves.clear()
    },
    handleDisagree(e) {
      this.disPopUp()
      privacyResolves.forEach(resolve => {
        resolve({
          event: 'disagree',
        })
      })

      wx.showToast({
        title: '请阅读并同意本小程序的相关协议和政策',
        icon: 'none',
        duration: 2500
      })
      privacyResolves.clear()
    },
    popUp() {
      if (this.data.innerShow === false) {
        this.setData({
          innerShow: true
        })
      }
    },
    disPopUp() {
      if (this.data.innerShow === true) {
        this.setData({
          innerShow: false
        })
      }
    },
    openPrivacyContract() {
      wx.openPrivacyContract({
        success: res => {
          console.log('openPrivacyContract success')
        },
        fail: res => {
          console.error('openPrivacyContract fail', res)
        }
      })
    },
    tips_link: function (e) {
      console.log(e)
      wx.navigateTo({
        url: '/pages/perfect/pages/singlepage/index?id=2'
      })
    }
  }
})